package view;

import view.statistik.StatistikPanel;
import view.kasse.BetalingsPanel;
import view.touchability.ScreenKeyboard;
import view.touchability.SkærmNumpad;
import view.lager.LagerPanel;
import view.kasse.KasseRapportPanel;
import view.kasse.KassePanel;
import databasehandling.DatabaseHandler;
import control.AnsatController;
import java.awt.AWTException;
import java.awt.CardLayout;
import java.io.IOException;
import java.sql.SQLException;
import java.text.ParseException;
import javax.swing.JOptionPane;
import utility.PageHandler;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Rectangle;
import java.awt.Toolkit;
import java.io.FileNotFoundException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.ImageIcon;
import model.EnhedsSalg;
import utility.ImageToolbox;
import utility.ScreenImage;
import view.kasse.TilføjEventPanel;

/**
 *
 * @author Maja Gliese
 */
public class MainGUI extends javax.swing.JFrame {

    private final PageHandler ph;
    private final MenuPanel menuPanel;
    private final LagerPanel lagerPanel;
    private final KassePanel kassePanel;
    private final TilføjEventPanel tilføjEventPanel;
    private final RabatPopUpPanel rabatPopUpPanel;
    private final BetalingsPanel betalingsPanel;
    private final KasseRapportPanel kasseRapportPanel;
    private final StatistikPanel statistikPanel;
    private final StartSkærm startSkærm;
    private final LoginPanel loginPanel;
    private final ScreenKeyboard screenKeyboard;
    private final SkærmNumpad skærmNumpad;

    public static final Color BUTTON_SELECTED_COLOR = new Color(145, 169, 191);
    public static final Color BUTTON_UNSELECTED_COLOR = new Color(208, 208, 208);
    public static final Color BUTTON_STANDARD_COLOR = new Color(208, 208, 208);

    public MainGUI() {
        initComponents();
        skærmNumpad = SkærmNumpad.getInstance();
        screenKeyboard = new ScreenKeyboard();
        screenKeyboard.setBounds(this.getBounds().x, this.getBounds().y + this.getBounds().height + 340, 800, 300);

        //<editor-fold defaultstate="collapsed" desc="DatabaseLogin">
        boolean connected = false;
        try {
            DatabaseHandler.getInstance().openConn("ini.txt");
            connected = true;
        } catch (SQLException ex) {
            JOptionPane.showMessageDialog(this, "Fejl 1000 \nKunne ikke oprette forbindelse til serveren\nPrøv evt. igen senere. Serveren kan være nede." + ex.getLocalizedMessage(), "Databasetimeout", 0);
        } catch (ClassNotFoundException ex) {
            JOptionPane.showMessageDialog(this, "Fejl 1030 \nDriveren blev ikke fundet.\nKontakt systemadministratoren." + ex.getLocalizedMessage(), "Fejl", 0);
        } catch (ParseException ex) {
            JOptionPane.showMessageDialog(this, "Fejl 1021 \nFejl ved læsning af inifilen. Login oplysninger i ini-filen er blevet ændret af en bruger.\n" + ex.getMessage(), "Fejl", 0);
        } catch (FileNotFoundException ex) {
            System.err.println("Filen 'ini.txt' blev ikke fundet. Vi forsøger at logge på med standard oplysninger.");
        } catch (IOException ex) {
            JOptionPane.showMessageDialog(this, "Fejl 1050 \nKunne ikke skrive den nye ini-fil." + ex.getLocalizedMessage(), "Fejl", 0);
        }
        if (!connected) {
            try {
                DatabaseHandler.getInstance().openConn(null);
            } catch (SQLException ex) {
                JOptionPane.showMessageDialog(this, "Fejl 1000 \nKunne ikke oprette forbindelse til serveren\nPrøv evt. igen senere. Serveren kan være nede" + ex.getLocalizedMessage(), "Databasetimeout", 0);
            } catch (ClassNotFoundException ex) {
                JOptionPane.showMessageDialog(this, "Fejl 1030 \nDriveren blev ikke fundet.\nKontakt systemadministratoren" + ex.getLocalizedMessage(), "Fejl", 0);
            } catch (IOException ex) {
                JOptionPane.showMessageDialog(this, "Fejl 1055 \nIni-fil eksisterer ikke endnu. Er nu oprettet. \nGenstart programmet" + ex.getLocalizedMessage(), "Fejl", 0);
            } catch (ParseException ex) {
                JOptionPane.showMessageDialog(this, "Fejl 1022 \nFejl ved læsning af inifilen. Data passer ikke overens.\n" + ex.getMessage(), "Fejl", 0);
            }
        }
//</editor-fold>
        ph = new PageHandler((CardLayout) cardLayoutPanel.getLayout(), cardLayoutPanel);
        menuPanel = new MenuPanel(this);
        lagerPanel = new LagerPanel(this);
        kassePanel = new KassePanel(this);
        tilføjEventPanel = new TilføjEventPanel(this, kassePanel);
        rabatPopUpPanel = new RabatPopUpPanel(this, kassePanel);
        kasseRapportPanel = new KasseRapportPanel(this);
        statistikPanel = new StatistikPanel(this);
        betalingsPanel = new BetalingsPanel(this, kassePanel);
        startSkærm = new StartSkærm(this);
        loginPanel = new LoginPanel(this);
        ph.addPage(menuPanel, "MenuPanel");
        ph.addPage(lagerPanel, "LagerPanel");
        ph.addPage(kassePanel, "KassePanel");
        ph.addPage(tilføjEventPanel, "TilføjEventPanel");
        ph.addPage(rabatPopUpPanel, "RabatPopUpPanel");
        ph.addPage(betalingsPanel, "BetalingsPanel");
        ph.addPage(startSkærm, "StartSkærm");
        ph.addPage(loginPanel, "LoginPanel");
        ph.addPage(kasseRapportPanel, "KasseRapportPanel");
        ph.addPage(statistikPanel, "StatistikPanel");
        showPage("StartSkærm");
        updateBanner();
        setSize(802, 722);
        setLocationRelativeTo(null);
        setLocation(getX(), 15);
        setIcon();
    }

    public SkærmNumpad getSkærmNumpad() {
        return skærmNumpad;
    }

    public void visTilføjEventPanel(ImageIcon screenShotOfKassePanel) {
        ph.show("TilføjEventPanel");
        tilføjEventPanel.setScreenShotBaggrund(screenShotOfKassePanel);
    }

    /**
     * Denne metode er til at vise betalingsPanelet. Den bliver kaldt når
     * brugeren klikker på "Afslut-Knappen" i kassePanelet, og KUN dér.
     *
     * @param screenShotOfKassePanel et imageIcon af det aktuelle kassepanel.
     * Billedet bliver brugt til at danne baggrund i BetalingsPanel.
     */
    public void visBetalingsPanel(ImageIcon screenShotOfKassePanel) {
        ph.show("BetalingsPanel");
        betalingsPanel.setUltraBaggrund(screenShotOfKassePanel);
    }

    public void visRabatPopUp(ImageIcon screenShotOfKassePanel, EnhedsSalg enhedsSalg) {
        ph.show("RabatPopUpPanel");
        rabatPopUpPanel.setPanel(screenShotOfKassePanel, enhedsSalg);
    }

    public void visLoginPanel() {
        showPage("StartSkærm");
        Rectangle r = new Rectangle(startSkærm.getLocationOnScreen(), startSkærm.getSize());
        ImageIcon img = null;
        try {
            img = new ImageIcon(ScreenImage.createImage(r));
        } catch (AWTException ex) {
            Logger.getLogger(BetalingsPanel.class.getName()).log(Level.SEVERE, null, ex);
        }
        loginPanel.setScreenShotBaggrund(img);
        ph.show("LoginPanel");
        
    }

    public BetalingsPanel getBetalingspanel() {
        return betalingsPanel;
    }

    private void setIcon() {
        setIconImage(Toolkit.getDefaultToolkit().getImage(getClass().getResource("/images/logo.png")));
    }

    public void showPage(String ref) {
        ph.show(ref);
    }

    public void showScreenKeyboard() {
        if (screenKeyboard.isVisible()) {
            screenKeyboard.setVisible(false);
        } else {
            screenKeyboard.setVisible(true);
        }
        screenKeyboard.setLocation(getX() + 3, getY() + getHeight() - 80);
    }

    /**
     * Metoden sætter billede ud fra aktivAnsat variablen. Bruges til at vise om
     * en bruger er logget ind eller om der skal logges ind
     */
    public void updateBanner() {
        //<editor-fold defaultstate="collapsed" desc="SetLoginknapIcon">
        if (AnsatController.getInstance().getAktivAnsat() == null) {
            LoginKnap.setIcon(new ImageIcon(getClass().getResource("/images/logout-lock.png")));
            LoginKnap.repaint();
            aktivAnsatLabel.setText("Ingen");
            aktivAnsatLabel.setForeground(Color.RED);
        } else {
            LoginKnap.setIcon(new ImageIcon(getClass().getResource("/images/login-lock.png")));
            LoginKnap.repaint();
            aktivAnsatLabel.setText(AnsatController.getInstance().getAktivAnsat().toString());
            aktivAnsatLabel.setForeground(Color.BLACK);
        }
        //</editor-fold>  
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jMenuItem3 = new javax.swing.JMenuItem();
        cardLayoutPanel = new javax.swing.JPanel();
        bannerPanel = new javax.swing.JPanel();
        hjemKnap = new javax.swing.JButton(){
            public void paint(Graphics g){
                ImageToolbox.drawImage(g, (ImageIcon) hjemKnap.getIcon(), 0, 0, hjemKnap.getWidth(), hjemKnap.getHeight());
            }
        };
        visScreenKeyboardKnap = new javax.swing.JButton(){
            public void paint(Graphics g){
                ImageToolbox.drawImage(g, (ImageIcon) visScreenKeyboardKnap.getIcon(), 0, 0, visScreenKeyboardKnap.getWidth(), visScreenKeyboardKnap.getHeight());
            }
        };
        LoginKnap = new javax.swing.JButton(){
            public void paint(Graphics g){
                ImageToolbox.drawImage(g, (ImageIcon) LoginKnap.getIcon(), 0, 0, LoginKnap.getWidth(), LoginKnap.getHeight());
            }
        };
        aktivAnsatLabel = new javax.swing.JLabel();
        brugerTitelLabel = new javax.swing.JLabel();
        bannerLabel = new javax.swing.JLabel(){
            public void paint(Graphics g){
                ImageToolbox.drawImage(g, (ImageIcon) bannerLabel.getIcon(), 0, 0, bannerLabel.getWidth(), bannerLabel.getHeight());
            }
        };
        baggrund = new javax.swing.JLabel(){
            public void paint(Graphics g){
                ImageToolbox.drawImage(g, (ImageIcon) baggrund.getIcon(), 0, 0, baggrund.getWidth(), baggrund.getHeight());
            }
        };
        jMenuBar1 = new javax.swing.JMenuBar();
        AfslutMenuKnap = new javax.swing.JMenu();
        loginMenuItem = new javax.swing.JMenuItem();
        visSkærmTastetuMenuKnap = new javax.swing.JMenuItem();
        jSeparator1 = new javax.swing.JPopupMenu.Separator();
        jMenuItem2 = new javax.swing.JMenuItem();
        jMenu2 = new javax.swing.JMenu();
        jMenuItem1 = new javax.swing.JMenuItem();

        jMenuItem3.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_1, java.awt.event.InputEvent.CTRL_MASK));
        jMenuItem3.setText("jMenuItem3");
        jMenuItem3.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jMenuItem3ActionPerformed(evt);
            }
        });

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setTitle("Museum Sydøstdanmark");
        setBackground(new java.awt.Color(204, 204, 204));
        setResizable(false);
        addWindowFocusListener(new java.awt.event.WindowFocusListener() {
            public void windowGainedFocus(java.awt.event.WindowEvent evt) {
                formWindowGainedFocus(evt);
            }
            public void windowLostFocus(java.awt.event.WindowEvent evt) {
                formWindowLostFocus(evt);
            }
        });
        addWindowListener(new java.awt.event.WindowAdapter() {
            public void windowClosed(java.awt.event.WindowEvent evt) {
                formWindowClosed(evt);
            }
        });
        addComponentListener(new java.awt.event.ComponentAdapter() {
            public void componentMoved(java.awt.event.ComponentEvent evt) {
                formComponentMoved(evt);
            }
        });
        getContentPane().setLayout(null);

        cardLayoutPanel.setBackground(new java.awt.Color(255, 255, 255));
        cardLayoutPanel.setOpaque(false);
        cardLayoutPanel.setLayout(new java.awt.CardLayout());
        getContentPane().add(cardLayoutPanel);
        cardLayoutPanel.setBounds(0, 60, 800, 610);

        bannerPanel.setBackground(new java.awt.Color(255, 255, 255));
        bannerPanel.setLayout(null);

        hjemKnap.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/homeIcon.png"))); // NOI18N
        hjemKnap.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                hjemKnapActionPerformed(evt);
            }
        });
        bannerPanel.add(hjemKnap);
        hjemKnap.setBounds(5, 4, 50, 50);

        visScreenKeyboardKnap.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/keyboard.png"))); // NOI18N
        visScreenKeyboardKnap.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                visScreenKeyboardKnapActionPerformed(evt);
            }
        });
        bannerPanel.add(visScreenKeyboardKnap);
        visScreenKeyboardKnap.setBounds(60, 7, 50, 50);

        LoginKnap.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/login-lock.png"))); // NOI18N
        LoginKnap.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                LoginKnapActionPerformed(evt);
            }
        });
        bannerPanel.add(LoginKnap);
        LoginKnap.setBounds(735, 4, 50, 50);

        aktivAnsatLabel.setForeground(new java.awt.Color(255, 51, 51));
        aktivAnsatLabel.setText("Ingen");
        bannerPanel.add(aktivAnsatLabel);
        aktivAnsatLabel.setBounds(612, 20, 120, 14);

        brugerTitelLabel.setText("Bruger:");
        bannerPanel.add(brugerTitelLabel);
        brugerTitelLabel.setBounds(570, 20, 40, 14);

        bannerLabel.setBackground(new java.awt.Color(255, 255, 255));
        bannerLabel.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/bannerGradient.png"))); // NOI18N
        bannerPanel.add(bannerLabel);
        bannerLabel.setBounds(0, 0, 800, 60);

        getContentPane().add(bannerPanel);
        bannerPanel.setBounds(0, 0, 800, 60);

        baggrund.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/baggrund.png"))); // NOI18N
        getContentPane().add(baggrund);
        baggrund.setBounds(0, 60, 810, 610);

        AfslutMenuKnap.setText("File");

        loginMenuItem.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_F2, 0));
        loginMenuItem.setText("Login");
        loginMenuItem.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                loginMenuItemActionPerformed(evt);
            }
        });
        AfslutMenuKnap.add(loginMenuItem);

        visSkærmTastetuMenuKnap.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_E, java.awt.event.InputEvent.CTRL_MASK));
        visSkærmTastetuMenuKnap.setText("Vis Skærm tastatur");
        visSkærmTastetuMenuKnap.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                visSkærmTastetuMenuKnapActionPerformed(evt);
            }
        });
        AfslutMenuKnap.add(visSkærmTastetuMenuKnap);
        AfslutMenuKnap.add(jSeparator1);

        jMenuItem2.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_F4, java.awt.event.InputEvent.ALT_MASK));
        jMenuItem2.setText("Afslut");
        jMenuItem2.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jMenuItem2ActionPerformed(evt);
            }
        });
        AfslutMenuKnap.add(jMenuItem2);

        jMenuBar1.add(AfslutMenuKnap);

        jMenu2.setText("Indstillinger");

        jMenuItem1.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_I, java.awt.event.InputEvent.CTRL_MASK));
        jMenuItem1.setText("DatabaseLogin");
        jMenuItem1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jMenuItem1ActionPerformed(evt);
            }
        });
        jMenu2.add(jMenuItem1);

        jMenuBar1.add(jMenu2);

        setJMenuBar(jMenuBar1);

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void loginMenuItemActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_loginMenuItemActionPerformed
        if (AnsatController.getInstance().getAktivAnsat() == null) {
            visLoginPanel();
        } else {
            AnsatController.getInstance().logOut();
            showPage("StartSkærm");
        }
        updateBanner();
    }//GEN-LAST:event_loginMenuItemActionPerformed

    private void formWindowClosed(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_formWindowClosed
        closeApplication();
    }//GEN-LAST:event_formWindowClosed

    private void jMenuItem2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenuItem2ActionPerformed
        closeApplication();
    }//GEN-LAST:event_jMenuItem2ActionPerformed

    private void visSkærmTastetuMenuKnapActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_visSkærmTastetuMenuKnapActionPerformed
        showScreenKeyboard();
    }//GEN-LAST:event_visSkærmTastetuMenuKnapActionPerformed

    private void LoginKnapActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_LoginKnapActionPerformed
        if (AnsatController.getInstance().getAktivAnsat() == null) {
            visLoginPanel();
        } else {
            AnsatController.getInstance().logOut();
            showPage("StartSkærm");
        }
        updateBanner();
    }//GEN-LAST:event_LoginKnapActionPerformed

    private void visScreenKeyboardKnapActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_visScreenKeyboardKnapActionPerformed
        showScreenKeyboard();
    }//GEN-LAST:event_visScreenKeyboardKnapActionPerformed

    private void formComponentMoved(java.awt.event.ComponentEvent evt) {//GEN-FIRST:event_formComponentMoved
        screenKeyboard.setLocation(this.getBounds().x, getY() + getHeight() - 80);

        if (kassePanel != null) {
            skærmNumpad.setLocation(this.getX() + kassePanel.getJPanel1Location().x + 110, this.getY() + kassePanel.getJPanel1Location().y + 90 + 112);
        }
    }//GEN-LAST:event_formComponentMoved

    private void hjemKnapActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_hjemKnapActionPerformed
        if (AnsatController.getInstance().getAktivAnsat() != null) {
            showPage("MenuPanel");
        } else {
            if(!ph.getCurrentPage().equals("LoginPanel")){
            visLoginPanel();
            }else{
                showPage("StartSkærm");
            }
        }
    }//GEN-LAST:event_hjemKnapActionPerformed

    private void formWindowLostFocus(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_formWindowLostFocus
//        if (ph.getCurrentPage().equals("KassePanel") || ph.getCurrentPage().equals("RabatPopUpPanel") || ph.getCurrentPage().equals("BetalingsPanel") || ph.getCurrentPage().equals("TilføjEventPanel")) {
        skærmNumpad.setVisible(false);
//        }
    }//GEN-LAST:event_formWindowLostFocus

    private void formWindowGainedFocus(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_formWindowGainedFocus
        if (ph.getCurrentPage().equals("KassePanel") || ph.getCurrentPage().equals("RabatPopUpPanel") || ph.getCurrentPage().equals("BetalingsPanel") || ph.getCurrentPage().equals("TilføjEventPanel")) {
            skærmNumpad.setVisible(true);
        }
    }//GEN-LAST:event_formWindowGainedFocus

    private void jMenuItem1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenuItem1ActionPerformed
        new Indstillinger(this, true).setVisible(true);
    }//GEN-LAST:event_jMenuItem1ActionPerformed

    private void jMenuItem3ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenuItem3ActionPerformed
        if (AnsatController.getInstance().getAktivAnsat() != null) {
            ph.show("LagerPanel");
        } else {
            System.out.println("Du er ikke logget ind endnu.");
        }
    }//GEN-LAST:event_jMenuItem3ActionPerformed

    /**
     * Lukker pænt programmet ned og afslutter forbindelsen mod databasen.
     */
    public void closeApplication() {
        try {
            DatabaseHandler.getInstance().closeConn();
            System.out.println("Forbindelsen er lukket");
            System.out.println("Programmet er lukket korrekt");
            System.exit(0);
        } catch (SQLException ex) {
            JOptionPane.showMessageDialog(this, "Fejl 1015 \nFejl ved lukning af forbindelsen til serveren.\nKontakt systemadministratoren." + ex.getMessage(), "Databasefejl", 0);
        }
    }

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JMenu AfslutMenuKnap;
    private javax.swing.JButton LoginKnap;
    private javax.swing.JLabel aktivAnsatLabel;
    private javax.swing.JLabel baggrund;
    private javax.swing.JLabel bannerLabel;
    private javax.swing.JPanel bannerPanel;
    private javax.swing.JLabel brugerTitelLabel;
    private javax.swing.JPanel cardLayoutPanel;
    private javax.swing.JButton hjemKnap;
    private javax.swing.JMenu jMenu2;
    private javax.swing.JMenuBar jMenuBar1;
    private javax.swing.JMenuItem jMenuItem1;
    private javax.swing.JMenuItem jMenuItem2;
    private javax.swing.JMenuItem jMenuItem3;
    private javax.swing.JPopupMenu.Separator jSeparator1;
    private javax.swing.JMenuItem loginMenuItem;
    private javax.swing.JButton visScreenKeyboardKnap;
    private javax.swing.JMenuItem visSkærmTastetuMenuKnap;
    // End of variables declaration//GEN-END:variables
}
